<template>
  <Card>
    <Tabs v-if="detail.name" type="card" :value="tabId" @on-click="tabChange" style="margin-top:20px;" >
      <TabPane label="用户信息" name="name0">
        <Form :model="detail" :label-width="150" ref="detail" :rules="ruleValidate">
          <h3 class="form-tip">
            基本信息
            <Icon style="margin-left: 5px;" type="compose"></Icon>
          </h3>
          <Row>
            <FormItem label="昵称：" prop="name">
              <Input style="width: 250px;" v-model="detail.name"/>
            </FormItem>
          </Row>
          <Row>
            <FormItem label="手机：" prop="mobile">
              <Input style="width: 250px;" v-model="detail.mobile"/>
            </FormItem>
          </Row>
          <Row>
            <FormItem label="渠道来源：" prop="channelSrc">
              <RadioGroup v-model="detail.channelSrc">
                <Radio :label="1">寿险渠道</Radio>
                <Radio :label="2">同行渠道</Radio>
                <Radio :label="3">入围公司</Radio>
                <Radio :label="4">其他渠道</Radio>
              </RadioGroup>
            </FormItem>
          </Row>
          <Row>
            <FormItem label="创建时间：" prop="createTime">
              {{detail.createTime}}
            </FormItem>
          </Row>
          <Row>
            <FormItem label="最后登入时间：" prop="updateTime">
              {{detail.updateTime}}
            </FormItem>
          </Row>
          <h3 class="form-tip">
            银行卡信息
            <Icon style="margin-left: 5px;" type="ios-card"></Icon>
          </h3>
          <Row>
            <i-col span="12">
              <FormItem label="持卡人姓名：" >
                <Input style="width: 250px;" v-model="detail.bankCardUserName"/>
              </FormItem>
            </i-col>
            <i-col span="12">
              <FormItem label="开户行：">
                <Input style="width: 250px;" v-model="detail.bank"/>
              </FormItem>
            </i-col>
          </Row>
          <Row>
            <FormItem label="银行账号：" >
              <Input style="width: 250px;" v-model="detail.bankCardNumber"/>
            </FormItem>
          </Row>
          <h3 class="form-tip">
            其他信息
            <Icon style="margin-left: 5px;" type="md-bulb" ></Icon>
          </h3>
          <Row>
            <FormItem label="我的上级(团长)：">
              {{detail.leaderName}}
            </FormItem>
          </Row>
          <Row>
            <FormItem label="客户经理" prop="managerName" v-if="userType === 2">
              <Select  style="width: 250px;" v-model="detail.managerName" placeholder="请选择客户经理" class="searchItem" @on-change="chooseManager">
                <Option v-for=" (item,index) in managerList " :key="index" :value="item.adminName">{{item.adminName}}</Option>
              </Select>
            </FormItem>
          </Row>
          <Row>
            <i-col span="12">
              <FormItem label="佣金：" >
                <p style="display: inline-block">{{detail.reward}}</p>
                <Button style="display: inline-block;margin-left:50px;" type="primary" @click="changeMoney">更改</Button>
              </FormItem>
            </i-col>
            <i-col span="12">
              <FormItem label="密码：" prop="charmValue">
                <Button style="display: inline-block;margin-left:50px;" type="primary" @click="changePwd('charm')">更改</Button>
              </FormItem>
            </i-col>
          </Row>
          <Row>
            <FormItem>
              <Button type="primary" :loading="saveLoading" @click="save('detail')">保存</Button>
            </FormItem>
          </Row>
        </Form>
      </TabPane>
      <TabPane label="我的客户" name="name1">
        <Customer v-if="this.tabId === 'name1'"></Customer>
      </TabPane>
      <TabPane label="我的团队" name="name2">
        <Team v-if="this.tabId === 'name2'"></Team>
      </TabPane>
      <TabPane label="佣金变更记录" name="name3">
        <Reward v-if="this.tabId === 'name3'"></Reward>
      </TabPane>
    </Tabs>
  </Card>
</template>

<script>
import {getChina} from '@/libs/city'
import {
  getUserDetail,
  editUser,
  editReward,
  editPassword,
  getAdmin
} from '@/api/user'
import Customer from './customer'
import Team from './team'
import Reward from './reward'

export default {
  components: {
    Customer,
    Team,
    Reward
  },
  name: 'user-detail',
  data () {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'));
      } else {
        if (this.pawForm.passwdCheck !== '') {
          // 对第二个密码框单独验证
          console.log(this.$refs)
          this.$refs.pawForm.validateField('passwdCheck');
        }
        callback();
      }
    };
    const validatePassCheck = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.pawForm.passwd) {
        callback(new Error('两次密码不同'));
      } else {
        callback();
      }
    };
    return {
      userType: this.$store.state.user.userType,
      tabId: 0,
      managerList: [],
      pawForm: {
        passwd: '1',
        passwdCheck: '2'
      },
      detail: {},
      resDefault: [],
      ruleValidate: {
        name: [
          {required: true, message: '昵称不能为空', trigger: 'blur'}
          ],
        mobile: [
          {required: true, message: '手机号码不能为空', trigger: 'blur'}
        ],
        channelSrc: [
          {required: true, type:'number', message: '渠道来源不能为空', trigger: 'blur'}
        ]
        // bankCardUserName: [
        //   {required: true, message: '持卡人姓名不能为空', trigger: 'blur'}
        // ],
        // bank: [
        //   {required: true, message: '开户行不能为空', trigger: 'blur'}
        // ],
        // bankCardNumber: [
        //   {required: true,  message: '银行账号不能为空', trigger: 'blur'}
        // ]
      },
      ruleValidate2: {
        passwd: [{validator: validatePass, trigger: 'blur'}, {
          type: 'string',
          min: 6,
          message: '密码不能短于6位',
          trigger: 'blur'
        }],
        passwdCheck: [{validator: validatePassCheck, trigger: 'blur'}, {
          type: 'string',
          min: 6,
          message: '密码不能短于6位',
          trigger: 'blur'
        }]
      },
      saveLoading: false,
      sign: 1,
      changeScore: 0
    }
  },
  methods: {
    tabChange (name) {
      this.tabId = name
    },
    getDetail() {
      const data = {
        cid: this.$route.query.id,
        adminId: this.userType === 1? this.$store.state.user.userId:''
      }
      getUserDetail(data).then( data => {
        this.detail = data
      }, error => {
        if(error === '您无权限') {
          this.$router.replace('401')
        }
      })
    },
    chooseManager (data) {
      console.log(data)
      this.managerList.forEach( item => {
        if (item.adminName === data) {
          this.detail.managerMobile = item.mobile
          this.detail.managerName = item.adminName
          this.detail.adminId = item.id
        }
      })
    },
    changeMoney () {
      if (this.userType !== 2) {
        this.$Message.error('您暂无权限');
        return
      }
      this.$Modal.confirm({
        loading: true,
        render: (h) => {
          return h('div', [
            h('RadioGroup', {
              props: {
                value: this.sign
              },
              style: {
                marginTop: '10px'
              },
              on: {
                'on-change': (currentValue) => { this.sign = currentValue }
              }
            }, [
              h('Radio', {
                props: {
                  label: 1
                }
              }, '加'),
              h('Radio', {
                props: {
                  label: 2
                }
              }, '减')
            ]),
            h('InputNumber', {
              props: {
                value: this.changeScore,
                min: 0
              },
              style: {
                width: '100%',
                marginTop: '15px'
              },
              on: {
                input: (val) => {
                  this.changeScore = val
                }
              }
            })
          ])
        },
        onOk: () => {
          let params ={
            cid: parseInt(this.$route.query.id),
            sign: this.sign,
            money: this.changeScore
          }
          editReward(params).then(() => {
            this.$Modal.remove();
            this.$Message.info('修改成功');
            this.getDetail();
            this.sign =  1;
            this.changeScore = 0
          }, error => {
            this.$Modal.remove();
            this.$Message.info(error)
          })
        },
        onCancel: () => {
          this.changeScore = 0
        }
      })
    },
    changePwd () {
      if (this.userType !== 2) {
        this.$Message.error('您暂无权限');
        return
      }
      this.$Modal.confirm({
        loading: true,
        render: () => {
          let create = this.$createElement
          let model = create('div',{}, [
            create('Form', {
              props: {
                model: this.pawForm,
                labelWidth: 150,
                rules: this.ruleValidate2
              },
              ref:'pawForm'
            },[
              create('FormItem', {
                props: {
                  label:"请输入新的密码:",
                  prop: "passwd"
                }
              }, [
                create('Input', {
                  props: {
                    type: 'password',
                    value: this.pawForm.passwd
                  },
                  style: {
                    width: '100%',
                  },
                  on: {
                    input: (val) => {
                      this.pawForm.passwd = val
                    }
                  }
                })
              ]),
              create('FormItem', {
                props: {
                  label: "请再次输入新的密码:",
                  prop: "passwdCheck"
                }
              }, [
                create('Input', {
                  props: {
                    type: 'password',
                    value: this.pawForm.passwdCheck

                  },
                  style: {
                    width: '100%',
                  },
                  on: {
                    input: (val) => {
                      this.pawForm.passwdCheck = val
                    }
                  }
                })
              ])
            ])
          ])
          return model
        },
        onOk: () => {
          console.log(this.$refs)
          let params ={
            cid: parseInt(this.$route.query.id),
            password: this.pawForm.passwd,
          }
          editPassword(params).then(() => {
            this.$Modal.remove();
            this.$Message.info('修改成功');
          }, error => {
            this.$Modal.remove();
            this.$Message.info(error)
          })
        },
        onCancel: () => {
        }
      })
    },
    changeResDefault (newValue) {
      this.detail.hometown = [newValue[0].name,newValue[1].name,newValue[2].name]
    },
    save (name) {
      if (this.userType !== 2) {
        this.$Message.error('您暂无权限');
        return
      }
      this.saveLoading = true
      this.$refs[name].validate((valid) => {
        if (valid) {
          const data = Object.assign({}, this.detail)
          editUser(data).then(() => {
            this.$Message.success('修改成功')
            this.saveLoading = false
            this.getDetail()
          }, error => {
            this.saveLoading = false
          })
        } else {
          this.$Message.error('修改失败')
          this.saveLoading = false
        }
      })
    }
  },
  mounted () {
    this.getDetail()
    if (this.userType === 2) {
      getAdmin().then(data => {
        this.managerList = data
      })
    }
  }
}
</script>

<style scoped>

</style>
